import { TextBox } from "../types";

/**
 * 将 TextBox 数组按页分组，再按段分组
 * @param textBoxes TextBox 数组
 * @returns 分组后的结构 { [pageIndex]: { [paragraphIndex]: TextBox[] } }
 */
export function groupTextBoxes(textBoxes: TextBox[]): Record<number, Record<number, TextBox[]>> {
  const groupedByPage: Record<number, Record<number, TextBox[]>> = {};

  // 第一层分组：按 pageIndex
  for (const box of textBoxes) {
    const page = box.data.pageIndex;
    const paragraph = box.data.paragraphIndex;

    if (!groupedByPage[page]) {
      groupedByPage[page] = {};
    }
    if (!groupedByPage[page][paragraph]) {
      groupedByPage[page][paragraph] = [];
    }
    groupedByPage[page][paragraph].push(box);
  }

  return groupedByPage;
}
export const createParagraphRects = (textBoxes: TextBox[]) => {
  // 按行分组：使用 {pageIndex}-{rowIndex} 作为复合键
  const lineGroups: Record<string, TextBox[]> = {};
  
  textBoxes.forEach(box => {
    const page = box.data.pageIndex;
    const line = box.data.rowIndex; // 假设 TextBox 结构中有 rowIndex
    const key = `${page}-${line}`;
    
    if (!lineGroups[key]) {
      lineGroups[key] = [];
    }
    lineGroups[key].push(box);
  });

  // 为每行生成最大矩形
  return Object.values(lineGroups).map(lineBoxes => {
    let minX = Infinity;
    let minY = Infinity;
    let maxX = -Infinity;
    let maxY = -Infinity;

    lineBoxes.forEach(box => {
      minX = Math.min(minX, box.x);
      minY = Math.min(minY, box.y);
      maxX = Math.max(maxX, box.x + box.width);
      maxY = Math.max(maxY, box.y + box.height);
    });

    return {
      x: minX,
      y: minY,
      width: maxX - minX,
      height: maxY - minY,
      pageIndex: lineBoxes[0].data.pageIndex,
      rowIndex: lineBoxes[0].data.rowIndex,
      paragraphIndex: lineBoxes[0].data.paragraphIndex,
    };
  });
};